<template>
  <common-header @refresh-cards="fetchAllCardInfo" />
  <div class="content-container">    <!-- 分类选择区域 -->
    <div class="filter-section">
      <!-- 分类方式选择 -->
      <n-space align="center" :size="24" class="filter-type-selection">
        <n-text strong>分类方式：</n-text>
        <n-radio-group v-model:value="filterType" name="filterType">
          <n-radio-button value="bodyPart">按锻炼部位</n-radio-button>
          <n-radio-button value="gymType">按场馆类型</n-radio-button>
        </n-radio-group>
      </n-space>
      
      <!-- 锻炼部位分类标签 -->
      <n-tabs 
        v-if="filterType === 'bodyPart'" 
        type="line" 
        animated 
        class="tabs" 
        v-model:value="currentBodyPartTab"
      >
        <n-tab-pane name="all" tab="全部" />
        <n-tab-pane name="chest" tab="胸部训练" />
        <n-tab-pane name="back" tab="背部训练" />
        <n-tab-pane name="shoulder" tab="肩部训练" />
        <n-tab-pane name="leg" tab="腿部训练" />
        <n-tab-pane name="arm" tab="手臂训练" />
        <n-tab-pane name="multi" tab="多功能器械" />
      </n-tabs>
      
      <!-- 场馆类型分类标签 -->
      <n-tabs 
        v-if="filterType === 'gymType'" 
        type="line" 
        animated 
        class="tabs" 
        v-model:value="currentGymTypeTab"
      >
        <n-tab-pane name="all" tab="全部" />
        <n-tab-pane name="gym" tab="健身房" />
        <n-tab-pane name="yoga" tab="瑜伽馆" />
        <n-tab-pane name="boxing" tab="拳击馆" />
        <n-tab-pane name="dance" tab="舞蹈室" />
        <n-tab-pane name="swimming" tab="游泳馆" />
        <n-tab-pane name="outdoor" tab="户外健身" />
      </n-tabs>
    </div>

    <!-- 器械卡片网格 -->    <div class="card-grid">
      <n-card
          v-for="item in filteredEquipments"
          :key="item.cardId"
          class="equipment-card"
          :bordered="false"
          hoverable
          @click="handleCardClick(item)"
      >        <!-- 器械图片 -->
        <div class="equipment-image-container">
          <n-image
            :src="item.coverImg ? BASE_URL + item.coverImg : '/default_equipment.svg'"
            class="equipment-image"
            preview-disabled
            object-fit="scale-down"
            :alt="item.title"
            fallback-src="/default_equipment.svg"
            :img-props="{ style: 'width: 100%; height: auto; display: block;' }"
          />
        </div>
          <!-- 器械基本信息 -->
        <n-space vertical :size="12" class="equipment-info">
          <n-text strong class="equipment-name">{{ item.title }}</n-text>
          
          <n-flex justify="space-between" align="center">
            <n-tag :bordered="false" type="info" size="small">
              {{ item.bodyPart }}
            </n-tag>
            
            <n-space align="center" :size="12">
              <n-button text @click.stop="handleLike(item)">
                <template #icon>
                  <n-icon :color="item.isLiked ? '#2080f0' : ''">
                    <ThumbsUp v-if="item.isLiked" />
                    <ThumbsUpOutline v-else />
                  </n-icon>
                </template>
                {{ item.likeCount }}
              </n-button>
              <n-button text>
                <template #icon>
                  <n-icon><ChatbubbleEllipses /></n-icon>
                </template>
                {{ item.commentCount }}
              </n-button>
            </n-space>
          </n-flex>
            <!-- 教练编辑按钮 -->
          <n-flex v-if="isCoach && currentUserCardIds.has(item.cardId)" justify="center" style="margin-top: 12px;">
            <n-button 
              type="primary" 
              size="small" 
              @click.stop="handleEditCard(item)"
              style="width: 100%;"
            >
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
              编辑器械卡片
            </n-button>
          </n-flex>
        </n-space>
      </n-card>
    </div>    <!-- 详情弹窗 -->
    <n-modal v-model:show="showDetailModal" preset="card" style="width: 600px; max-width: 90vw;">
      <n-card :bordered="false" content-style="padding: 0;" class="detail-card">        <!-- 器械图片 -->
        <div class="detail-image-container">
          <n-image
            :src="currentCardInfo?.coverImg ? BASE_URL + currentCardInfo.coverImg : '/default_equipment.svg'"
            class="detail-image"
            preview-disabled
            object-fit="scale-down"
            fallback-src="/default_equipment.svg"
            :img-props="{ style: 'width: 100%; height: auto; display: block;' }"
          />
        </div>

        <!-- 器械基本信息 -->
        <div class="detail-content">
          <!-- 标题 -->
          <n-h2>{{ currentCardInfo?.title }}</n-h2
          >
          
          <!-- 使用指导说明 -->
          <n-space vertical size="large" class="guide-section">
            <n-space vertical>
              <n-text strong>使用指导说明</n-text>
              <n-text class="guide-text">{{ currentCardInfo?.usageGuide }}</n-text>
            </n-space>

            <!-- 安全注意事项 -->
            <n-space vertical>
              <n-text strong type="warning">安全注意事项</n-text>
              <n-text class="safety-text" type="warning">{{ currentCardInfo?.precautions }}</n-text>
            </n-space>

            <!-- 推荐课程 -->
            <n-space vertical v-if="recommendedCourses.length">
              <n-divider />
              <n-text strong>相关课程推荐</n-text>
              <n-grid :cols="3" :x-gap="12">
                <n-grid-item v-for="course in recommendedCourses" :key="course.courseId">
                  <n-card class="course-card" :bordered="false" hoverable @click="handleCourseClick(course)">                    <n-image
                      :src="course.coverImg ? BASE_URL + course.coverImg : '/default_course.svg'"
                      class="course-image"
                      preview-disabled
                      object-fit="contain"
                      fallback-src="/default_course.svg"
                    />
                    <n-text strong class="course-title">{{ course.title }}</n-text>                    <!-- 简化教练信息展示 -->
                    <n-flex align="center" class="coach-info">
                      <n-avatar
                        round
                        size="small"
                        :src="course.coach?.avatarImgUrl ? BASE_URL + course.coach.avatarImgUrl : '/default_avatar.svg'"
                        @click.stop="handleCoachAvatarClick(course.coach)"
                        class="clickable-avatar"
                      />
                      <n-text class="coach-name" @click.stop="handleCoachAvatarClick(course.coach)">{{ course.coach?.nickname }}</n-text>
                    </n-flex>
                  </n-card>
                </n-grid-item>
              </n-grid>
            </n-space>

            <!-- 时间信息 -->
            <n-space justify="space-between" align="center">
              <n-text depth="3" size="small">创建时间：{{ currentCardInfo?.createTime }}</n-text>
              <n-text depth="3" size="small">更新时间：{{ currentCardInfo?.updateTime }}</n-text>
            </n-space>
          </n-space>

          <!-- 评论区 -->
          <n-divider />
          <div class="comment-section">
            <n-space vertical :size="16">
              <!-- 评论计数 -->
              <n-flex justify="space-between" align="center">
                <n-text strong>评论</n-text>
                <n-tag :bordered="false" size="small" type="info">{{ currentCardInfo?.commentCount || 0 }}</n-tag>
              </n-flex>

              <!-- 评论输入框 -->
              <n-input
                v-model:value="newComment"
                type="textarea"
                placeholder="写下你的评论..."
                :autosize="{ minRows: 2, maxRows: 4 }"
              />
              <n-button
                block
                type="primary"
                @click="handleSendComment"
                :disabled="!newComment.trim()"
              >
                发送评论
              </n-button>              <!-- 评论列表 -->
              <template v-if="currentCardInfo?.parsedComments?.length">
                <n-thing
                  v-for="comment in currentCardInfo.parsedComments"
                  :key="comment.commentId"
                  class="comment-item"
                >
                  <template #avatar>
                    <n-avatar
                      :src="comment.avatarImgUrl ? BASE_URL + comment.avatarImgUrl : '/default_avatar.svg'"
                      round
                      :size="40"
                      fallback-src="/default_avatar.svg"
                    />
                  </template>
                  <template #header>
                    <n-space align="center" :size="8">
                      <n-text strong>{{ comment.nickname || comment.userNickname }}</n-text>
                      <n-text depth="3" size="tiny">{{ comment.createTime }}</n-text>
                    </n-space>
                  </template>
                  <template #description>
                    <n-text depth="2">{{ comment.content }}</n-text>
                  </template>
                </n-thing>
              </template>
              <template v-else>
                <n-empty description="暂无评论" />
              </template>
            </n-space>
          </div>        </div>
      </n-card>
    </n-modal>

    <!-- 编辑器械卡片弹窗 -->
    <n-modal v-model:show="showEditModal" preset="dialog" title="编辑器械卡片">
      <template #header>
        <div>编辑器械卡片</div>
      </template>
      <n-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-placement="left"
        label-width="100"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="器械名称" path="title">
          <n-input v-model:value="editForm.title" placeholder="请输入器械名称" />
        </n-form-item>
        <n-form-item label="锻炼部位" path="bodyPart">
          <n-select
            v-model:value="editForm.bodyPart"
            :options="bodyPartOptions"
            placeholder="请选择锻炼部位"
          />
        </n-form-item>
        <n-form-item label="使用指导" path="usageGuide">
          <n-input
            v-model:value="editForm.usageGuide"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入使用指导说明"
          />
        </n-form-item>
        <n-form-item label="注意事项" path="precautions">
          <n-input
            v-model:value="editForm.precautions"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入安全注意事项"
          />
        </n-form-item>
        <n-form-item label="器械图片" path="coverImg">
          <n-upload
            :custom-request="handleEditImageUpload"
            :file-list="editImageList"
            @change="handleEditImageChange"
            accept="image/*"
            :max="1"
            list-type="image-card"
          >
            点击上传图片
          </n-upload>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button type="primary" @click="saveCardEdit" :loading="editLoading">保存</n-button>        </n-space>
      </template>
    </n-modal>
    
    <!-- 教练信息弹窗 -->
    <CoachInfoPopup
      v-model:show="showCoachInfoPopup"
      :user-id="selectedCoachUserId"
      :coach-info="selectedCoachInfo"
    />
  </div>
</template>

<script setup>
import CommonHeader from '../components/CommonHeader.vue'
import CoachInfoPopup from '../components/CoachInfoPopup.vue'
import { NIcon, NButton, NFlex, NCard, NTabs, NTabPane, NAvatar, NPopover, NDivider, NRadioGroup, NRadioButton } from 'naive-ui';
import router from "../router/index";
import { onMounted, watch, ref, computed } from 'vue';
import axios from 'axios';
import http from '../utils/http.js';
import { useMessage } from 'naive-ui';
import { ChatbubbleEllipses, ThumbsUp, ThumbsUpOutline, CaretDown, Send, CreateOutline } from '@vicons/ionicons5'

const BASE_URL = window.BASE_URL

// 获取用户信息的工具函数
function getUser() {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
}

const message = useMessage();
const userInfo = ref(getUser());

// 一进入页面就：
// 检查登录状态
onMounted(() => {
  checkLoginStatus();
  console.log("用户信息:", userInfo.value);
});

// 检查用户是否登录
const checkLoginStatus = async () => {
  try {
    const loginResponse = await axios.post(BASE_URL+'/v1/user/isLogin');
    if (loginResponse.data.data) {
      // 已登录则获取最新用户信息
      const currentUser = JSON.parse(localStorage.user || '{}');
      const userResponse = await axios.get(BASE_URL+'/v1/user/select', {
        params: {
          username: currentUser.username
        }
      });
      if (userResponse.data.code === 2000) {
        const userData = {
          ...userResponse.data.data,
          tokenInfo: currentUser.tokenInfo
        };
        localStorage.user = JSON.stringify(userData);
        userInfo.value = userData;
      }
    } else {
      userInfo.value = null;
      localStorage.removeItem('user');
      await router.push('/login');
    }
  } catch (error) {
    console.error('检查登录状态失败:', error);
    userInfo.value = null;
    localStorage.removeItem('user');
    if (error.response && error.response.status === 401) {
      await router.push('/login');
    }
  }
};

//跳转到登录
const login = () => {
  router.push('/login');
}

const center = () => {
  router.push('/user/center');
}

// 退出登录
const logout = async () => {
  try {
    const response = await axios.post(BASE_URL+'/v1/user/logout');
    if (response.data.code === 2000) {
      message.success("退出登录成功");
      //退出时清空localStorage
      localStorage.removeItem('user');
      userInfo.value = null;
      await router.push('/login');
    } else {
      message.error("退出登录失败");
    }
  } catch (error) {
    console.error('退出登录失败:', error);
    message.error("退出登录失败，请稍后重试");
  }
};

// 详情弹窗控制
const showDetailModal = ref(false)
const currentCardInfo = ref(null)

// 评论相关数据
const comments = ref([])
const newComment = ref('')
const expandedComments = ref(new Set())

// 当前选中的分类方式和标签页
const filterType = ref('bodyPart') // 'bodyPart' 或 'gymType'
const currentBodyPartTab = ref('all')
const currentGymTypeTab = ref('all')

// 器械分类映射
const areaMapping = {
  '胸部': 'chest',
  '背部': 'back',
  '肩部': 'shoulder',
  '腿部': 'leg',
  '手臂': 'arm',
  '多功能': 'multi'
}

// 场馆器械映射字典 - 根据器械名称判断属于哪种场馆
const gymEquipmentMapping = {
  // 健身房器械
  'gym': [
    '杠铃', '哑铃', '史密斯机', '龙门架', '卧推架', '深蹲架', '推胸器', '高拉训练器',
    '坐姿划船器', '腿举机', '腿弯举机', '腿伸展器', '小腿训练器', '蝴蝶机', '双杠',
    '引体向上器', '综合训练器', '力量架', '多功能训练器', '跑步机', '椭圆机', 
    '动感单车', '划船机', '台阶机', '健身车', '健身器械', '力量器械', '有氧器械'
  ],
  
  // 瑜伽馆器械
  'yoga': [
    '瑜伽垫', '瑜伽球', '瑜伽砖', '瑜伽带', '瑜伽轮', '瑜伽椅', '瑜伽抱枕',
    '瑜伽毯', '平衡垫', '平衡球', '平衡板', '普拉提器械', '普拉提垫', '伸展带',
    '泡沫轴', '按摩球', '瑜伽圈', '瑜伽绳', '冥想垫', '瑜伽辅具'
  ],
  
  // 拳击馆器械
  'boxing': [
    '拳击袋', '沙袋', '速度球', '梨球', '拳击手套', '护手带', '拳击台',
    '重型沙袋', '立式沙袋', '吊式沙袋', '拳击垫', '护具', '靶子', '拳击器械',
    '格斗训练器', '速度训练器', '反应球', '拳击架', '训练靶', '格斗装备'
  ],
  
  // 舞蹈室器械
  'dance': [
    '舞蹈把杆', '镜子', '音响设备', '地胶', '舞蹈垫', '舞蹈鞋', '舞蹈服',
    '拉伸带', '舞蹈辅具', '平衡训练器', '柔韧性训练器', '舞蹈器材',
    '舞蹈训练器', '律动训练器', '舞蹈道具', '形体训练器'
  ],
  
  // 游泳馆器械
  'swimming': [
    '游泳池', '浮板', '浮条', '脚蹼', '游泳圈', '潜水镜', '游泳帽',
    '鼻夹', '耳塞', '水中哑铃', '水中训练器', '游泳训练器', '水中健身器械',
    '游泳辅具', '水上器械', '水中运动器材', '游泳装备'
  ],
  
  // 户外健身器械 - 户外运动和自然环境训练
  'outdoor': [
    '单杠', '双杠', '户外健身器械', '公园健身器材', '户外拉伸器', '户外力量器械',
    '户外有氧器械', '攀爬架', '平衡木', '户外训练器', '自然训练器',
    '户外运动器材', '野外训练器', '户外健身设备', '公共健身器材'
  ]
}

// 根据器械名称判断所属场馆类型
const getGymTypeByEquipmentName = (equipmentName) => {
  for (const [gymType, equipments] of Object.entries(gymEquipmentMapping)) {
    // 使用包含匹配，支持部分匹配
    if (equipments.some(equipment => 
      equipmentName.includes(equipment) || equipment.includes(equipmentName)
    )) {
      return gymType
    }
  }  return 'gym' // 默认归类为健身房
}

// 所有器械卡片列表
const allCardInfo = ref([]);

// 获取所有器械卡片列表
const fetchAllCardInfo = async () => {
  try {
    const response = await axios.get(BASE_URL + '/v1/card/select'); 
    if (response.data.code === 2000) {
      allCardInfo.value = response.data.data;
      
      // 初始化每个卡片的点赞状态和数据
      const user = getUser();
      if (user) {
        // 如果用户已登录，获取真实的点赞状态和数量
        for (const card of allCardInfo.value) {
          try {
            const likeResponse = await http.get('/v1/like/status', {
              params: {
                targetId: card.cardId,
                targetType: 1
              }
            });
            if (likeResponse.data.code === 2000) {
              card.isLiked = likeResponse.data.data.isLiked;
              card.likeCount = likeResponse.data.data.likeCount;
            } else {
              card.isLiked = false;
              card.likeCount = card.likeCount || 0;
            }
          } catch (error) {
            console.warn('获取点赞状态失败:', error);
            card.isLiked = false;
            card.likeCount = card.likeCount || 0;
          }
        }
      } else {
        // 如果用户未登录，初始化默认值
        allCardInfo.value.forEach(card => {
          card.isLiked = false;
          card.likeCount = card.likeCount || 0;
        });      }
      
      // 更新当前用户的卡片ID集合
      await updateCurrentUserCards()
      
      console.log("获取器械列表成功:", allCardInfo.value);
    } else {
      message.error(response.data.msg || '获取器械列表失败');
    }
  } catch (error) {
    console.error('获取器械列表失败:', error);
    message.error('获取器械列表失败，请稍后重试');
  }
};

// 评论数据解析函数
const parseComments = (contentStr) => {
  try {
    // 移除字符串两端的方括号
    const str = contentStr.substring(1, contentStr.length - 1);
    // 解析CommentVO对象
    const regex = /CommentVO\(([^)]+)\)/g;
    const matches = str.match(regex);
    
    if (!matches) return [];
    
    return matches.map(match => {
      // 提取括号内的内容
      const content = match.substring(9, match.length - 1);
      // 分割属性
      const parts = content.split(', ');
      const comment = {};
      
      parts.forEach(part => {
        const [key, value] = part.split('=');
        comment[key] = value === 'null' ? null : value;
      });
      
      return comment;
    });
  } catch (error) {
    console.error('解析评论数据失败:', error);
    return [];
  }
};

// 处理卡片点击的函数
const handleCardClick = async (item) => {
  currentCardInfo.value = item;
  showDetailModal.value = true;
  // 获取推荐课程
  await fetchRecommendedCourses(item.title);
  // 获取评论
  await refreshComments();
};

// 刷新评论列表
const refreshComments = async () => {
  if (!currentCardInfo.value) return;
  
  try {
    const response = await axios.get(`${BASE_URL}/api/comments/target/${currentCardInfo.value.cardId}/1`);
    if (response.data.code === 2000) {
      currentCardInfo.value.parsedComments = response.data.data || [];
      currentCardInfo.value.commentCount = currentCardInfo.value.parsedComments.length;
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 推荐课程数据
const recommendedCourses = ref([]);

// 获取推荐课程
const fetchRecommendedCourses = async (equipmentName) => {
  try {
    const response = await axios.get(BASE_URL + '/v1/course/select')
    if (response.data.code === 2000) {
      // 筛选与当前器械相关的课程,只显示前3个
      const filteredCourses = response.data.data
        .filter(course => course.equipmentName === equipmentName)
        .slice(0, 3)
        // 为每个课程获取教练信息
      const coursesWithCoachInfo = await Promise.all(
        filteredCourses.map(async (course) => {
          try {
            // 先获取教练信息，再获取用户信息
            const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId?userId=${course.coachId}`)
            if (coachResponse.data.code === 2000 && coachResponse.data.data) {
              const coachData = coachResponse.data.data
              // 使用教练的userId获取用户信息
              const userResponse = await axios.get(`${BASE_URL}/v1/user/selectByUserId?userId=${coachData.userId}`)
              if (userResponse.data.code === 2000) {
                course.coach = userResponse.data.data
              }
            }
          } catch (error) {
            console.error('获取教练信息失败:', error)
            course.coach = null
          }
          return course
        })
      )
      
      recommendedCourses.value = coursesWithCoachInfo
    }
  } catch (error) {
    console.error('获取推荐课程失败:', error)
  }
}

// 处理课程点击
const handleCourseClick = (course) => {
  router.push({
    path: '/course',
    query: { courseId: course.courseId }
  });
}

// 处理教练头像点击
const handleCoachAvatarClick = (coach) => {
  console.log('点击了教练头像，参数:', coach);
  console.log('coach类型:', typeof coach);
  console.log('coach内容:', JSON.stringify(coach, null, 2));
  
  if (!coach) {
    console.log('教练数据为空，函数返回');
    return;
  }
  
  // 检查用户身份是否为教练（role = 2）
  if (coach.role !== 2) {
    console.log('用户身份不是教练，role:', coach.role, '不弹出教练信息弹窗');
    message.info('该用户不是教练');
    return;
  }
  
  console.log('设置教练信息，userId:', coach.userId);
  selectedCoachUserId.value = coach.userId;
  selectedCoachInfo.value = coach;
  showCoachInfoPopup.value = true;
  console.log('弹窗状态已设置为 true');
}

// 点赞状态
const isLiked = ref(false)

// 处理器械点赞
const handleLike = async (item) => {
  if (!item) return;
  
  const user = getUser();
  if (!user) {
    message.warning('请先登录');
    return;
  }
    try {
    const response = await http.post('/v1/like/toggle', {
      targetId: item.cardId || item.id,
      targetType: 1 // 器械卡片类型为1
    });if (response.data.code === 2000) {
      const likeData = response.data.data;
      
      // 使用服务器返回的准确数据
      item.isLiked = likeData.isLiked;
      item.likeCount = likeData.likeCount;
      
      message.success(likeData.isLiked ? '点赞成功' : '已取消点赞');
    } else {
      message.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('点赞失败:', error);
    message.error('操作失败，请稍后重试');
  }
}

// 添加显示评论的函数
const showComments = (item) => {
  currentCardInfo.value = item;
  showDetailModal.value = true;
}

// 处理评论点赞
const handleCommentLike = (comment) => {
  comment.isLiked = !comment.isLiked
  comment.likes += comment.isLiked ? 1 : -1
}

// 处理展开/折叠回复
const toggleReplies = (commentId) => {
  if (expandedComments.value.has(commentId)) {
    expandedComments.value.delete(commentId)
  } else {
    expandedComments.value.add(commentId)
  }
}

// 发送评论
const handleSendComment = async () => {
  if (!newComment.value.trim()) {
    message.warning('请输入评论内容');
    return;
  }
  
  const user = getUser();
  if (!user) {
    message.warning('请先登录');
    return;
  }
  
  try {
    const response = await axios.post(`${BASE_URL}/api/comments`, {
      targetId: currentCardInfo.value.cardId,
      targetType: 1, // 器械卡片类型为1
      content: newComment.value.trim(),
      userId: user.userId
    });
    
    if (response.data.code === 2000) {
      message.success('评论成功');
      newComment.value = '';
      // 重新获取评论列表
      await refreshComments();
    } else {
      message.error(response.data.msg || '评论失败');
    }
  } catch (error) {
    console.error('评论失败:', error);
    message.error('评论失败，请稍后重试');
  }
}

// 发布器械相关的响应式数据
const showPublishModal = ref(false)
const publishFormRef = ref(null)
const publishing = ref(false)
const coverImgList = ref([])

// 编辑器械相关的响应式数据
const showEditModal = ref(false)
const editFormRef = ref(null)
const editLoading = ref(false)
const editImageList = ref([])

// 教练信息弹窗相关的响应式数据
const showCoachInfoPopup = ref(false)
const selectedCoachUserId = ref(null)
const selectedCoachInfo = ref(null)

const editForm = ref({
  cardId: null,
  title: '',
  bodyPart: null,
  usageGuide: '',
  precautions: '',
  coverImg: ''
})

const publishForm = ref({
  title: '',
  bodyPart: null,
  usageGuide: '',
  precautions: '',
  coverImg: ''
})

// 锻炼部位选项
const bodyPartOptions = [
  { label: '胸部', value: '胸部' },
  { label: '背部', value: '背部' },
  { label: '肩部', value: '肩部' },
  { label: '腿部', value: '腿部' },
  { label: '手臂', value: '手臂' },
  { label: '多功能', value: '多功能' }
]

// 表单验证规则
const publishRules = {
  title: {
    required: true,
    message: '请输入器械名称',
    trigger: ['blur', 'input']
  },
  bodyPart: {
    required: true,
    message: '请选择锻炼部位',
    trigger: ['blur', 'change']
  },
  usageGuide: {
    required: true,
    message: '请输入使用指导说明',
    trigger: ['blur', 'input']
  },
  coverImg: {
    required: true,
    message: '请上传器械图片',
    trigger: ['blur', 'change']
  }
}

// 编辑表单验证规则
const editRules = {
  title: {
    required: true,
    message: '请输入器械名称',
    trigger: ['blur', 'input']
  },
  bodyPart: {
    required: true,
    message: '请选择锻炼部位',
    trigger: ['blur', 'change']
  },
  usageGuide: {
    required: true,
    message: '请输入使用指导说明',
    trigger: ['blur', 'input']
  },
  precautions: {
    required: true,
    message: '请输入安全注意事项',
    trigger: ['blur', 'input']
  },
  coverImg: {
    required: true,
    message: '请上传器械图片',
    trigger: ['blur', 'change']
  }
}

// 处理器械图片上传
const handleCoverUpload = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  
  return axios.post(BASE_URL+'/v1/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    if (response.data.code === 2000) {
      publishForm.value.coverImg = response.data.data
      message.success('图片上传成功')
    }
  }).catch(error => {
    console.error('图片上传失败:', error)
    message.error('图片上传失败，请稍后重试')
  })
}

// 处理器械图片改变
const handleCoverChange = (options) => {
  const { file } = options
  if (file.status === 'finished') {
    coverImgList.value = [{
      id: 'cover',
      name: file.name,
      status: 'finished',
      url: file.url
    }]
  }
}

// 处理器械图片删除
const handleCoverRemove = () => {
  if (publishForm.value.coverImg) {
    axios.post(BASE_URL+'/v1/file/remove', qs.stringify({
      imgUrl: publishForm.value.coverImg
    })).then(response => {
      if (response.data.code === 2000) {
        publishForm.value.coverImg = ''
        coverImgList.value = []
        message.success('图片已删除')
      }
    }).catch(error => {
      console.error('图片删除失败:', error)
      message.error('图片删除失败，请稍后重试')
    })
  }
}

// 发布器械
const handlePublish = () => {
  publishFormRef.value?.validate(async (errors) => {
    if (!errors) {
      publishing.value = true
      try {
        const user = getUser()
        if (!user) {
          throw new Error('用户未登录')
        }
        
        // 获取教练信息
        const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId`, {
          params: {
            userId: user.userId
          }
        })
        
        if (coachResponse.data.code !== 2000) {
          throw new Error('获取教练信息失败')
        }

        if (!coachResponse.data.data?.coachId) {
          throw new Error('教练ID不存在')
        }

        const coachId = coachResponse.data.data.coachId
        console.log('教练ID:', coachId)
        
        // 设置coachId
        const cardData = {
          ...publishForm.value,
          coachId: coachId
        }
        
        const response = await axios.post(BASE_URL+'/v1/card/insert', cardData)
        if (response.data.code === 2000) {
          message.success('发布成功')
          showPublishModal.value = false
          // 重置表单
          publishForm.value = {
            title: '',
            bodyPart: null,
            usageGuide: '',
            precautions: '',
            coverImg: ''
          }
          coverImgList.value = []
          // 刷新器械列表
          await fetchAllCardInfo()
        } else {
          throw new Error(response.data.msg || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        message.error(error.message || '发布失败，请稍后重试')
      } finally {
        publishing.value = false
      }
    } else {
      message.error('请检查表单填写是否正确')
    }
  })
}

// 添加教练身份判断
const isCoach = computed(() => userInfo.value?.role === 2)

// 存储当前用户拥有的卡片ID
const currentUserCardIds = ref(new Set())

// 更新当前用户的卡片ID集合
const updateCurrentUserCards = async () => {
  if (!userInfo.value || userInfo.value.role !== 2) {
    currentUserCardIds.value.clear()
    return
  }
  
  try {
    // 先获取当前用户的教练信息
    const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId?userId=${userInfo.value.userId}`)
    if (coachResponse.data.code === 2000 && coachResponse.data.data) {
      const currentUserCoachId = coachResponse.data.data.coachId
      
      // 找出当前用户发布的卡片
      const cardIds = new Set()
      for (const item of allCardInfo.value) {
        if (item.coachId === currentUserCoachId) {
          cardIds.add(item.cardId)
        }
      }
      currentUserCardIds.value = cardIds
      
      console.log('当前用户的教练ID:', currentUserCoachId)
      console.log('当前用户的卡片ID列表:', Array.from(cardIds))
    }
  } catch (error) {
    console.error('获取当前用户教练信息失败:', error)
    currentUserCardIds.value.clear()
  }
}

// 判断当前用户是否拥有该器械卡片
const isCurrentUserCard = async (item) => {
  if (!userInfo.value || !item) return false;
  
  try {
    // 获取教练信息，比较教练的userId
    const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId?userId=${item.coachId}`)
    if (coachResponse.data.code === 2000 && coachResponse.data.data) {
      return userInfo.value.userId === coachResponse.data.data.userId;
    }
  } catch (error) {
    console.error('获取教练信息失败:', error)
  }
  return false;
}

// 处理编辑器械卡片
const handleEditCard = (item) => {
  // 填充编辑表单数据
  editForm.value = {
    cardId: item.cardId,
    title: item.title,
    bodyPart: item.bodyPart,
    usageGuide: item.usageGuide,
    precautions: item.precautions,
    coverImg: item.coverImg
  };

  // 设置图片列表用于显示
  if (item.coverImg) {
    editImageList.value = [{
      id: 'cover',
      name: 'cover.jpg',
      status: 'finished',
      url: BASE_URL + item.coverImg
    }];
  } else {
    editImageList.value = [];
  }
  showEditModal.value = true;
}

// 编辑器械卡片保存
const saveCardEdit = async () => {
  try {
    await editFormRef.value?.validate();
    editLoading.value = true;    // 构造更新数据
    const updateData = {      cardId: editForm.value.cardId,
      coachId: userInfo.value.userId, // 添加当前用户的ID作为教练ID
      title: editForm.value.title,
      bodyPart: editForm.value.bodyPart,
      usageGuide: editForm.value.usageGuide,
      precautions: editForm.value.precautions,
      coverImg: editForm.value.coverImg
    };

    console.log('发送更新数据:', updateData);

    const response = await axios.post(`${BASE_URL}/v1/card/update`, updateData);
    if (response.data.code === 2000) {
      message.success('更新成功');
      showEditModal.value = false;
      // 刷新器械列表
      await fetchAllCardInfo();
    } else {
      message.error(response.data.msg || '更新失败');
    }
  } catch (error) {
    console.error('更新器械卡片失败:', error);
    if (error.message) {
      message.error('请检查表单填写是否正确');
    } else {
      message.error('更新失败');
    }
  } finally {
    editLoading.value = false;
  }
};

// 处理编辑时的图片上传
const handleEditImageUpload = async ({ file, onFinish, onError }) => {
  const formData = new FormData();
  formData.append('file', file.file);

  try {
    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (response.data.code === 2000) {
      editForm.value.coverImg = response.data.data;
      file.url = BASE_URL + response.data.data;
      message.success('图片上传成功');
      onFinish();
    } else {
      message.error(response.data.msg || '图片上传失败');
      onError();
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    message.error('图片上传失败');
    onError();
  }
};

// 处理编辑时的图片变更
const handleEditImageChange = (options) => {
  const { file, fileList } = options;
  editImageList.value = fileList;
  
  if (file.status === 'finished') {
    editForm.value.coverImg = file.url.replace(BASE_URL, '');
  } else if (file.status === 'removed') {
    editForm.value.coverImg = '';
    editImageList.value = [];
  }
};

// 在页面加载时获取数据
onMounted(async () => {
  // 先检查登录状态
  await checkLoginStatus();
  // 获取器械列表数据
  await fetchAllCardInfo();
});

// 修改筛选计算属性
const filteredEquipments = computed(() => {
  if (!allCardInfo.value) return [];
  
  let filtered = [...allCardInfo.value];
  
  // 根据分类方式和选中的标签进行筛选
  if (filterType.value === 'bodyPart') {
    // 按锻炼部位筛选
    if (currentBodyPartTab.value !== 'all') {
      filtered = filtered.filter(item => 
        areaMapping[item.bodyPart] === currentBodyPartTab.value
      );
    }
  } else if (filterType.value === 'gymType') {
    // 按场馆类型筛选
    if (currentGymTypeTab.value !== 'all') {
      filtered = filtered.filter(item => 
        getGymTypeByEquipmentName(item.title) === currentGymTypeTab.value
      );
    }
  }
  
  // 按点赞数排序（降序）
  return filtered.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0));
});
</script>

<style scoped>
/* 整体布局样式 */
.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 分类选择区域样式 */
.filter-section {
  margin-bottom: 20px;
  background: #fafafa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e0e0e0;
}

.filter-type-selection {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

/* 标签页导航样式 */
.tabs {
  margin-bottom: 0;
}

/* 卡片网格布局 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
  align-items: stretch; /* 确保所有卡片高度一致 */
}

/* 器械卡片样式 - 使用内部网格布局 */
.equipment-card {
  transition: all 0.3s ease;
  display: grid;
  grid-template-rows: 200px 1fr; /* 固定图片区域高度，内容区域自适应 */
  height: 380px; /* 固定卡片总高度 */
  overflow: hidden;
}

.equipment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 外部器械卡片图片样式 */
.equipment-image-container {
  width: 100%;
  height: 100%; /* 填满网格区域 */
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.equipment-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  object-fit: scale-down;
  transition: transform 0.3s ease;
  display: block;
}

/* 器械卡片样式 - 使用内部网格布局 */
.equipment-card {
  transition: all 0.3s ease;
  display: grid;
  grid-template-rows: 200px 1fr; /* 固定图片区域高度，内容区域自适应 */
  height: 380px; /* 固定卡片总高度 */
  overflow: hidden;
}

.equipment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.equipment-info {
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%; /* 填满剩余空间 */
  min-height: 0; /* 允许flex子项收缩 */
}

.equipment-name {
  font-size: 18px;
  line-height: 1.4;
  margin-bottom: 12px;
  flex-shrink: 0; /* 标题不收缩 */
}

.equipment-card:hover .equipment-image {
  transform: scale(1.05);
}

/* 详情弹窗样式 */
.detail-card {
  max-height: 90vh;
  overflow-y: auto;
  overflow-x: hidden; /* 隐藏横向滚动条 */
}

.detail-image-container {
  width: 100%;
  max-height: 400px;
  background-color: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  box-sizing: border-box;
}

.detail-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  object-fit: scale-down;
  border-radius: 4px;
}

.detail-content {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.guide-section {
  margin: 20px 0;
}

.comment-section {
  margin-top: 24px;
}

/* 评论区样式 */
.comments-section {
  margin-top: 32px;
}

.comment-input {
  margin-bottom: 24px;
}

.comment {
  padding: 16px 0;
  border-bottom: 1px solid var(--n-border-color);
}

.send-button {
  margin-top: 12px;
  width: 100%;
}

/* 添加时间信息样式 */
.detail-content .n-text {
  display: block;
  line-height: 1.6;
}

.comment-item {
  padding: 16px;
  border-bottom: 1px solid var(--n-border-color);
}
.comment-item:last-child {
  border-bottom: none;
}

/* 修改使用指导和注意事项的文本样式 */
.guide-text,
.safety-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.8;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  font-size: 15px;
  width: 100%;
  box-sizing: border-box;
  /* 删除max-height和overflow相关属性 */
}

.safety-text {
  background-color: #fff9f4;  /* 注意事项使用暖色背景 */
}

.guide-section :deep(.n-space) {
  width: 100%;  /* 确保内容占满宽度 */
  margin: 16px 0;  /* 增加区块间距 */
}

.guide-section :deep(.n-text) {
  margin: 12px 0;  /* 增加文本上下间距 */
}

/* 优化标题样式 */
.detail-content :deep(.n-h2) {
  margin: 16px 0;
  font-size: 24px;
  color: #333;
}

/* 轮播图样式 */
.carousel {
  height: 260px;
  width: 100%;
  margin: 16px 0;
}

.carousel-item {
  width: 280px;
  height: 100%;
  cursor: pointer;
}

/* 修改课程卡片相关样式 */
.course-card {
  background-color: #f9f9f9;
  transition: transform 0.3s ease;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-image {
  width: 100%;
  height: 120px;
  object-fit: contain;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 4px;
  box-sizing: border-box;
}

.coach-info {
  margin-top: 8px;
  gap: 8px;
}

.coach-name {
  font-size: 13px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s ease;
}

.coach-name:hover {
  color: #2080f0;
}

.clickable-avatar {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.clickable-avatar:hover {
  transform: scale(1.1);
}

.coach-popover {
  width: 280px;
  padding: 16px;
}

.coach-basic-info {
  width: 100%;
  padding: 8px 0;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
    padding: 15px 0;
  }
  
  .equipment-card {
    height: 340px; /* 中等屏幕减小卡片高度 */
    grid-template-rows: 180px 1fr; /* 调整图片区域高度 */
  }
  
  .detail-image-container {
    max-height: 300px;
    padding: 8px;
  }
  
  .content-container {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .card-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .equipment-card {
    height: 320px; /* 小屏幕进一步减小卡片高度 */
    grid-template-rows: 160px 1fr; /* 调整图片区域高度 */
  }
  
  .detail-image-container {
    max-height: 250px;
    padding: 6px;
  }
  
  .equipment-info {
    padding: 12px;
  }
  
  .detail-content {
    padding: 15px;
  }
}

/* 图片加载状态优化 */
.equipment-image:deep(.n-image) {
  background-color: #f8f9fa;
  border-radius: 8px;
}

.detail-image:deep(.n-image) {
  background-color: #f8f9fa;
  border-radius: 8px;
}

/* 图片容器样式优化 */
.equipment-card :deep(.n-image) {
  border-radius: 8px 8px 0 0;
  overflow: hidden;
}

.detail-card :deep(.n-image) {
  border-radius: 8px;
  overflow: hidden;
}
</style>